package com.i2works.smartluolong.utils.config;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * druid公共配置
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2017/12/14 9:34
 */

public class DruidConfigurationUtils {

    //登录地址
    private static final String LOGIN_PATH = "/druid/*";
    //登录用户名
    private static final String LOGIN_USERNAME = "smartluolong";
    //登录密码
    private static final String LOGIN_PASSWORD = "13303881010";



    /**
     * 注册
     *
     * @param loginPath     登录地址
     * @param loginUsername 登录用户名
     * @param loginPassword 登录密码
     */
    public static ServletRegistrationBean druidServlet(String loginPath, String loginUsername, String loginPassword) {
        if (StringUtils.isBlank(loginPath)) {
            loginPath = LOGIN_PATH;
        }
        if (StringUtils.isBlank(loginUsername)) {
            loginUsername = LOGIN_USERNAME;
        }
        if (StringUtils.isBlank(loginPassword)) {
            loginPassword = LOGIN_PASSWORD;
        }
        ServletRegistrationBean druid = new ServletRegistrationBean();
        druid.setServlet(new StatViewServlet());
        druid.setUrlMappings(Collections.singletonList(loginPath));
        Map<String, String> params = new HashMap<>();
        params.put("loginUsername", loginUsername);
        params.put("loginPassword", loginPassword);
        druid.setInitParameters(params);
        return druid;
    }

    /**
     * 拦截规则
     *
     * @param loginPath 登录地址
     */
    public static FilterRegistrationBean filter(String loginPath) {
        if (StringUtils.isBlank(loginPath)) {
            loginPath = LOGIN_PATH;
        }
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico," + loginPath);
        return filterRegistrationBean;
    }

}
